package com.example.weibo_suhuanzhen.homeRecycle;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.example.weibo_suhuanzhen.R;
import com.example.weibo_suhuanzhen.UserSession;
import com.example.weibo_suhuanzhen.activities.LoginActivity;
import com.example.weibo_suhuanzhen.adapters.MyAdapter;
import com.example.weibo_suhuanzhen.bean.WeiboInfo;
import com.example.weibo_suhuanzhen.homeRecycle.LikeCallback;
import com.example.weibo_suhuanzhen.retrofit.LikeManager;

public class VideoViewHolder extends RecyclerView.ViewHolder {
    private MyAdapter myAdapter;
    private SurfaceView surfaceView;//视频
    public ImageView thumbnail;
    private SeekBar seekBar;
    private TextView username;
    private ImageView avatar;//头像
    private TextView title;//文章标题
    private TextView like;//点赞数
    public ImageView playBtn;
    public MediaPlayer mediaPlayer;
    public boolean isPlaying = false;
    private String currentVideoUrl;
    private Context context;
    private final Handler handler = new Handler();
    private TextView currentTime;
    private TextView totalTime;
    ImageView im_like;//点赞图标
    boolean isLiked=false;
    private ImageView delete;

    private TextView comment;
    private LikeManager likeManager;

    private final Runnable updateSeekBar = new Runnable() {
        @Override
        public void run() {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                int currentPos = mediaPlayer.getCurrentPosition();
                seekBar.setProgress(currentPos);
                currentTime.setText(formatTime(currentPos));
                handler.postDelayed(this, 1000);
            }
        }
    };

    public VideoViewHolder(@NonNull View itemView, Context context, MyAdapter myAdapter) {
        super(itemView);
        this.context = context;
        this.myAdapter=myAdapter;
        surfaceView = itemView.findViewById(R.id.surface_view);
        thumbnail = itemView.findViewById(R.id.thumbnail);
        seekBar = itemView.findViewById(R.id.seek_bar);
        username = itemView.findViewById(R.id.username_in_video);
        avatar = itemView.findViewById(R.id.avatar_in_video);
        title = itemView.findViewById(R.id.title_in_video);
        like = itemView.findViewById(R.id.tv_like_inVideo);
        playBtn = itemView.findViewById(R.id.play_button);
        currentTime = itemView.findViewById(R.id.current_time);
        totalTime = itemView.findViewById(R.id.total_time);
        im_like = itemView.findViewById(R.id.im_like);
        delete = itemView.findViewById(R.id.delete_in_video);
        comment = itemView.findViewById(R.id.tv_comment);
        likeManager = new LikeManager(context);

        thumbnail.setVisibility(View.VISIBLE);

        playBtn.setOnClickListener(v -> {
            if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
                mediaPlayer.start();
                isPlaying = true;
                thumbnail.setVisibility(View.GONE);
                playBtn.setVisibility(View.GONE);
                handler.post(updateSeekBar);
            }
        });

        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                initializeMediaPlayer(currentVideoUrl, holder);
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                if (mediaPlayer != null) {
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.pause();
                        isPlaying = false;
                    }
                    mediaPlayer.setDisplay(null);
                }
            }
        });

        surfaceView.setOnClickListener(v -> {
            if (isPlaying) {
                mediaPlayer.pause();
                isPlaying = false;
                playBtn.setVisibility(View.VISIBLE);
            } else {
                mediaPlayer.start();
                isPlaying = true;
                thumbnail.setVisibility(View.GONE);
                playBtn.setVisibility(View.GONE);
                handler.post(updateSeekBar);
            }
        });
    }

    //视频处理
    private void initializeMediaPlayer(String videoUrl, SurfaceHolder holder) {
        try {
            if (mediaPlayer == null) {
                mediaPlayer = new MediaPlayer();
                mediaPlayer.setDisplay(holder);
                mediaPlayer.setOnPreparedListener(mp -> {
                    seekBar.setMax(mediaPlayer.getDuration());
                    seekBar.setEnabled(false);
                    totalTime.setText(formatTime(mediaPlayer.getDuration()));
                    mediaPlayer.setLooping(true);
                });
                mediaPlayer.setOnCompletionListener(mp -> mediaPlayer.seekTo(0));
                mediaPlayer.setOnBufferingUpdateListener((mp, percent) -> {
                    seekBar.setSecondaryProgress(percent * seekBar.getMax() / 100);
                });
                mediaPlayer.setOnSeekCompleteListener(mp -> {
                    int currentPos = mp.getCurrentPosition();
                    seekBar.setProgress(currentPos);
                    currentTime.setText(formatTime(currentPos+1));
                });
                mediaPlayer.setOnCompletionListener(mp -> {
                    mp.seekTo(0);
                    seekBar.setProgress(0);
                    currentTime.setText(formatTime(0));
                    handler.removeCallbacks(updateSeekBar);
                });
            } else {
                mediaPlayer.reset();
                mediaPlayer.setDisplay(holder);
            }
            mediaPlayer.setDataSource(context, Uri.parse(videoUrl));
            mediaPlayer.prepareAsync();
            currentVideoUrl = videoUrl;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void bind(WeiboInfo item, MyAdapter.ItemActionListener itemActionListener, int position) {
        Glide.with(context).load(item.getPoster()).into(thumbnail);
        Glide.with(context)
                .load(item.getAvatar())
                .transform(new CircleCrop())
                .into(avatar);
        username.setText(item.getUsername());
        title.setText(item.getTitle());
        like.setText(String.valueOf(item.getLikeCount()));

        currentVideoUrl = item.getVideoUrl();
        if (mediaPlayer != null) {
            mediaPlayer.reset();
            initializeMediaPlayer(currentVideoUrl, surfaceView.getHolder());
        }

        isLiked=item.isLikeFlag();
        if (isLiked){
            like.setTextColor(Color.parseColor("#e65231"));
            im_like.setImageResource(R.drawable.heart_red);
        }else {
            like.setTextColor(Color.parseColor("#000000"));
            im_like.setImageResource(R.drawable.heart);
        }

        //点赞逻辑
        like.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(!UserSession.getInstance().isLoggedIn()){
                    Intent intent = new Intent(context, LoginActivity.class);
                    context.startActivity(intent);
                }
                if (!isLiked){
                    likeManager.sendLike(item.getId(), new LikeCallback() {
                        @Override
                        public void onSuccess() {
                            like.setText(String.valueOf(item.getLikeCount() + 1));
                            item.setLikeCount(item.getLikeCount() + 1);
                            like.setTextColor(Color.parseColor("#e65231"));
                            im_like.setImageResource(R.drawable.heart_red);
                            performLike(im_like);
                            isLiked = true;
                        }

                        @Override
                        public void onFailure() {
                            Toast.makeText(context, "点赞失败，请检查网络", Toast.LENGTH_SHORT).show();
                        }
                    });
                }else {
                    likeManager.sendCancelLike(item.getId(), new LikeCallback() {
                        @Override
                        public void onSuccess() {
                            like.setText(String.valueOf(item.getLikeCount()-1));
                            item.setLikeCount(item.getLikeCount()-1);
                            like.setTextColor(Color.BLACK);
                            im_like.setImageResource(R.drawable.heart);
                            performCancelLike(im_like);
                            isLiked=false;
                        }
                        @Override
                        public void onFailure() {
                            Toast.makeText(context,"取消点赞失败，请检查网络", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });

        //评论点击
        comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) {
                    Toast.makeText(context,"点击第"+(position+1)+"条数据评论按钮",Toast.LENGTH_SHORT).show();
                }
            }
        });

        //删除视图
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) {
                    myAdapter.removeItem(position);
                }
            }
        });
    }

    private void performLike(View view) {
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 1f, 1.2f, 1f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1f, 1.2f, 1f);
        ObjectAnimator rotationY = ObjectAnimator.ofFloat(view, "rotationY", 0f, 360f);

        scaleX.setInterpolator(new AccelerateDecelerateInterpolator());
        scaleY.setInterpolator(new AccelerateDecelerateInterpolator());
        rotationY.setInterpolator(new AccelerateDecelerateInterpolator());

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(scaleX, scaleY, rotationY);
        animatorSet.setDuration(1000);
        animatorSet.start();
    }

    private void performCancelLike(View view) {
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 1f, 0.8f, 1f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1f, 0.8f, 1f);

        scaleX.setInterpolator(new AccelerateDecelerateInterpolator());
        scaleY.setInterpolator(new AccelerateDecelerateInterpolator());

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(scaleX, scaleY);
        animatorSet.setDuration(1000);
        animatorSet.start();
    }


    private String formatTime(int timeMs) {
        int totalSeconds = timeMs / 1000;
        int minutes = totalSeconds / 60;
        int seconds = totalSeconds % 60;
        return String.format("%02d:%02d", minutes, seconds);
    }


}